//
//  UIImages.swift
//  JXBaseTools
//
//  Created by godox on 2021/11/30.
//

import Foundation
import UIKit
import ImageIO

extension UIImage: JXCompatible{}
extension JX where Base: UIImage {
    
    /// SwifterSwift: UIImage with .alwaysOriginal rendering mode.
    var original: UIImage {
        return base.withRenderingMode(.alwaysOriginal)
    }
    //添加水印方法
    func waterMarkedImage(waterMarkText: String, corner: WaterMarkCorner = .BottomRight, margin: CGPoint = CGPoint(x: 20, y: 20), waterMarkTextColor: UIColor = UIColor.white, waterMarkTextFont: UIFont = UIFont.systemFont(ofSize: 20), backgroundColor: UIColor = UIColor.clear) -> UIImage {

        let textAttributes = [NSAttributedString.Key.foregroundColor:waterMarkTextColor, NSAttributedString.Key.font:waterMarkTextFont]
        let textSize = NSString(string: waterMarkText).size(withAttributes: textAttributes)
        var textFrame = CGRect(x: 0, y: 0, width: textSize.width, height: textSize.height)

        
        let imageSize = base.size
        switch corner{
            case .TopLeft:
                textFrame.origin = margin
            case .TopRight:
                textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: margin.y)
            case .BottomLeft:
                textFrame.origin = CGPoint(x: margin.x, y: imageSize.height - textSize.height - margin.y)
            case .BottomRight:
                textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: imageSize.height - textSize.height - margin.y)
        }

        // 开始给图片添加文字水印
        UIGraphicsBeginImageContext(imageSize)
        base.draw(in: CGRect(x: 0, y: 0, width:  imageSize.width, height:  imageSize.height))
        NSString(string: waterMarkText).draw(in: textFrame, withAttributes: textAttributes)

        let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return waterMarkedImage!
    }
}

public enum WaterMarkCorner {
    case TopLeft
    case TopRight
    case BottomLeft
    case BottomRight
}
